<template>
  <div>
    <el-dialog
      v-model="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="验收信息登记"
      width="1150"
      @close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="formParams"
        label-width="120px"
        style="margin: -20px"
        class="demo-ruleForm"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="验收合同" prop="rcId">
              <el-select
                placeholder="请选择验收合同"
                size="large"
                clearable
                @change="rcIdChange"
                v-model="formParams.rcId"
              >
                <el-option
                  v-for="item in contractTableLits"
                  :key="item.rcId"
                  :label="item.contractName"
                  :value="item.rcId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <avue-crud
          ref="xmCrud"
          :option="checkOption"
          :data="checkData"
          :class="{ maxHeight: !checkData.length }"
        >
          <template #actAccepTime-header="{ column }">
            <div class="avueIcon_style">{{ column.label }}</div>
          </template>
          <template #fileName-header="{ column }">
            <div class="avueIcon_style">{{ column.label }}</div>
          </template>
          <template #menu-left="{}">
            <slot name="selfDefined"></slot>
          </template>
          <slot></slot>
          <template #fileName="{ row, index }">
            <el-upload
              v-model:file-list="fileList[row.pcId]"
              class="upload-demo"
              action="#"
              :data-id="row.id"
              :http-request="changeFile"
              accept=".rar, .zip, .doc, .docx, .pdf"
              :show-file-list="false"
            >
              <el-button
                type="default"
                class="fileIcon_style"
                style="font-size: 12px; width: 80px"
                @click="asd(index)"
                >上传文件</el-button
              >
            </el-upload>
            <div
              class="text-14px mt-5px"
              style="width: 100%"
              v-if="row.origFileName"
            >
              <a :href="row.fileUrl" target="_blank" class="text-">{{
                row.origFileName
              }}</a>
              <el-button
                text
                plain
                type="primary"
                @click="delFileFn(index)"
                class="ml-10px"
                >删除</el-button
              >
            </div>
          </template>
          <template #menu="{ row, index }">
            <el-button
              text
              icon="Delete"
              type="primary"
              @click="rowCancel(row, index)"
              >删除</el-button
            >
          </template>
        </avue-crud>
        <div
          class="statistics"
          v-if="amountSum.length"
          style="
             {
              width: 100%;
            }
          "
        >
          <div class="statisticsBox">
            <div
              class="pr-10px"
              v-for="item in amountSum"
              :key="item.label + item.key"
            >
              {{ item.label }}:<span class="ml-5px">{{
                (item.unitPlace === 'before' ? item.unit : '') +
                total(item) +
                (item.unitPlace === 'after' ? item.unit : '')
              }}</span>
            </div>
          </div>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="通知人员：" prop="nameUUID">
              <el-select
                clearable
                v-model="formParams.nameUUID"
                placeholder="请选择通知人员"
                @focus="userInputFocusInit"
                class="w-full"
                multiple
              >
                <el-option
                  v-for="(item, index) in selectOptionObj['nameUUID']"
                  :key="index"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提醒方式：" prop="reminderMode">
              <el-checkbox-group v-model="information.reminderMode">
                <el-checkbox
                  v-for="(dict, index) in reminder_method"
                  :key="index"
                  :label="dict.value"
                >
                  {{ dict.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <SelectDialog
      :dialog-param="Notifyingdialog"
      @ok="selectNotifying"
      @close="Notifyingdialog.isDialog = false"
    />
  </div>
</template>
<script setup name="CheckAndAccept">
import { reactive, getCurrentInstance, watchEffect } from 'vue'
import EditTable from '@/views/salesManage/contractManage/newContract/EditTable.vue'
import useCommonStore from '@/store/modules/common'
import {
  checkProDelete,
  checkProUpdate,
  uploadFile,
  delFile,
  checkProList
} from '@/api/salesManage/contractManage'
import {
  project_phase, //项目阶段
  project_properties, //项目属性
  business_attribute, //业务属性
  project_amount, //项目金额
  bidding_form, //招标形式
  reminder_opening, //开标提醒(提醒时间)
  reminder_method, //提醒方式
  parentOptions,
  queryCustomer,
  companyOptions
} from '@/hooks/dict/useProject'
import { skipToError, getPricipalId, getTreeNodeByParam } from '@/utils/commo'
import { addManage, getLatestMsg } from '@/api/system/notice'
import useUserStore from '@/store/modules/user'
import { pushNotifications } from '@/hooks/notification/push'
import { format } from 'date-fns'
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const props = defineProps({
  checkParam: {
    required: true
  },
  //合同信息
  contractTable: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  },
  baseDetail: {
    required: true,
    type: Object,
    default: () => ({})
  }
})
const data = reactive({
  dialogFormVisible: true,
  formParams: {},
  // rules: {
  //   rcId: [
  //     {
  //       required: true,
  //       message: '验收合同不能为空',
  //       trigger: ['blur', 'change']
  //     }
  //   ]
  // },
  contractTableLits: [], //合同列表
  Notifyingdialog: {},
  SaleDialog: {},
  fileList: [], // 上传文件列表
  checkData: [],
  information: {
    notifyingOfficer: '',
    reminderMode: ['0'],
    name: ''
  },
  proMsgData: [],
  acceptMsg: {},
  selectOptionObj: {}
})
const {
  dialogFormVisible,
  formParams,
  rules,
  contractTableLits,
  Notifyingdialog,
  SaleDialog,
  fileList,
  checkData,
  information,
  proMsgData,
  acceptMsg,
  selectOptionObj
} = toRefs(data)

watch(
  () => props.checkParam,
  val => {
    dialogFormVisible.value = props.checkParam.visible
    contractTableLits.value = props.contractTable // JSON.parse(JSON.stringify(props.contractTable))
  },
  {
    deep: true,
    immediate: true
  }
)
const saveBtnNo = ref(true) //不要保存和编辑按钮
const pcId = ref('') //合同id
// 打开dialog触发
async function userInputFocusInit() {
  Notifyingdialog.value = {
    nodeKey: 'uuid',
    dataType: 'person',
    multiple: true,
    checkStrictly: false,
    title: '人员选择',
    defaultCheckedKeys: formParams.value.nameUUID || [],
    isDialog: true
  }
}
/*** 合同 验收 table 操作 start */
// 验收合同下拉框
async function rcIdChange(val) {
  checkData.value = []
  if (val) {
    // 获取验收计划信息
    const newCheckData = await checkProList(val)
    if (newCheckData.data && newCheckData.data.length > 0) {
      newCheckData.data.forEach(item => {
        checkData.value.push({
          ...item,
          ...{
            $cellEdit: true // 展示改行可编辑的数据
          }
        })
      })
    }
    pcId.value = val
    const respTb = await getLatestMsg({
      businessId: '项目-登记-' + val
    })
    if (respTb.code === 200 && respTb.data) {
      acceptMsg.value.reminderMethod = respTb.data.reminderMethod.split(',')
      acceptMsg.value.receiver = respTb.data.receiver
      acceptMsg.value.receiverName = respTb.data.receiverName
    } else {
      acceptMsg.value.reminderMethod = []
      acceptMsg.value.receiver = ''
      acceptMsg.value.receiverName = ''
    }
    information.value.notifyingOfficer = acceptMsg.value.receiver
    information.value.reminderMode =
      acceptMsg.value.reminderMethod &&
      acceptMsg.value.reminderMethod.length == 0
        ? ['0']
        : acceptMsg.value.reminderMethod
    information.value.name = acceptMsg.value.receiverName
    let idVal = acceptMsg.value.receiver
      ? acceptMsg.value.receiver.split(',')
      : []
    await getDefaultUserInfo(idVal)
  } else {
    checkData.value = []
    information.value.notifyingOfficer = ''
    information.value.name = ''
    formParams.value.nameUUID = []
  }
}
/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(id) {
  if (!id || JSON.stringify(id) == '[]') {
    return false
  }
  let arr = [],
    arrData = []
  let deptUserData = await commonStore.getUseTreeData()
  //获取人员数据
  id.map(item => {
    let res = getTreeNodeByParam(deptUserData, item, 'id', [])
    if (res && res.length > 0) {
      arrData.push(res[0])
      arr.push(res[0].uuid)
    }
  })
  selectOptionObj.value['nameUUID'] = arrData
  formParams.value.nameUUID = arr
}
// 设置底部统计内容
const amountSum = [
  {
    label: '总计划期数', // 字段名
    key: 'periodsNum', // 统计字段
    type: 'length', // length--数据长度  sum--字段求和   avg--字段平均数
    unit: '期', // 单位
    unitPlace: 'after' // 单位位置  前--before   后--after
  },
  {
    label: '总回款占比',
    key: 'planAccepRatio',
    type: 'sum',
    unit: '%',
    unitPlace: 'after'
  },
  {
    label: '总金额',
    key: 'planReturnSum',
    type: 'sum',
    unit: '￥',
    unitPlace: 'before'
  }
]
// 配置数据
const checkOption = reactive({
  align: 'left',
  border: true, // 边框
  delBtn: false, // 操作栏--删除
  columnBtn: false, // 列操作按钮
  editBtn: false, // 操作栏--编辑
  cancelBtn: false, // 表格取消按钮
  addBtn: false, // 表格新增按钮
  refreshBtn: false, // 表格刷新数据按钮
  menuWidth: 80,
  height: '280px',
  column: [
    {
      label: '期次',
      prop: 'periodsNum',
      width: '60'
      // rules: [
      //   {
      //     required: true,
      //     message: '请输入姓名',
      //     trigger: 'blur'
      //   }
      // ]
    },
    // {
    //   label: '阶段',
    //   prop: 'stage',
    //   rules: [
    //     {
    //       required: true,
    //       message: '请输入阶段',
    //       trigger: 'blur'
    //     }
    //   ]
    // },
    // {
    //   label: '条件',
    //   prop: 'conditions',
    //   rules: [
    //     {
    //       required: true,
    //       message: '请输入条件',
    //       trigger: 'blur'
    //     }
    //   ]
    // },
    {
      label: '计划验收日期',
      prop: 'planAccepDate',
      width: '110',
      // cell: true,// 在配置中将编辑的字段设置cell为true，开启行编辑
      // html: true, // 自定义列html内容
      format: val => `<span>${val}</span>` // val行数据
    },
    {
      label: '计划验收占比(%)',
      width: '130',
      prop: 'planAccepRatio'
    },
    {
      label: '计划回款金额(元)',
      width: '130',
      prop: 'planReturnSum'
    },
    {
      label: '实际验收时间',
      prop: 'actAccepTime',
      width: '150',
      // rules: [
      //   {
      //     required: true,
      //     message: '请选择实际验收时间',
      //     trigger: 'blur'
      //   }
      // ],
      formatter: (row, val) => {
        if (row.actAccepTime) {
          const date = new Date(row.actAccepTime)
          const format =
            date.getFullYear() +
            '-' +
            (date.getMonth() + 1 > 9
              ? date.getMonth() + 1
              : '0' + (date.getMonth() + 1)) +
            '-' +
            (date.getDate() + 1 > 9
              ? date.getDate() + 1
              : '0' + (date.getDate() + 1))
          return format
        } else {
          return ''
        }
      },
      cell: true, //可编辑的项
      type: 'date'
    },
    {
      label: '验收附件',
      prop: 'fileName'
      // rules: [
      //   {
      //     required: true,
      //     message: '请上传验收附件',
      //     trigger: 'blur'
      //   }
      // ]
      // cell: true
      // html: true, // 自定义列html内容
      // formatter: val => {
      //   return val.fileName === null
      //     ? `<input type="file" @change=${changeFile}'/>`
      //     : `<a href=${val.fileUrl}>${val.fileName}</a>       <butotn>预览</butotn
      // ><butotn plain text>删除</butotn>` // val行数据
      // }
    },
    {
      label: '备注',
      prop: 'remark',
      width: '170',
      cell: true
    }
  ]
})
// 表单按钮保存
const handleSave = () => {
  // proxy.$refs['ruleFormRef'].validate(valid => {
  // proxy.$refs['xmCrud'].validateCellForm().then(err => {
  // if (valid && !err) {
  const resp = bidOpeningMsg()
  if (!resp) {
    return
  }
  if (checkData.value.length) {
    const url = `/sales/projectManage/projectDetails?id=${props.baseDetail.projectId}`
    const Fdata = checkData.value.some(v => {
      return !v.fileName && v.actAccepTime
    })
    const Tdata = checkData.value.some(v => {
      return v.fileName && !v.actAccepTime
    })
    if (Fdata) {
      proxy.$modal.msgWarning('请上传验收附件')
      return
    }
    if (Tdata) {
      proxy.$modal.msgWarning('请输入实际验收时间')
      return
    }
    proMsgData.value.forEach(v => {
      v.url = url
      v.businessId = '项目-登记-' + pcId.value
      addManage(v)
    })

    checkProUpdate(checkData.value).then(res => {
      proxy.$modal.msgSuccess('保存成功')
      handleClose()
    })
  } else {
    proxy.$modal.msgWarning('验收信息登记列表暂无数据，不能操作')
    return
  }
  // }
  // else {
  //   skipToError()
  // }
  // })
  // })
}

// 行删除  取消/删除
function rowCancel(row, index) {
  proxy.$modal
    .confirm('是否确认删除?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      checkData.value.splice(index, 1)
      rowDelete(row, index)
    })
}
// 行删除
async function rowDelete(row, index) {
  try {
    const res = await checkProDelete(row.pcId)
    if (res.code === 200) {
      proxy.$modal.msgSuccess(res.data)
    }
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/*** 上传文件 */
const uploadIndex = ref(-1)
function asd(index) {
  uploadIndex.value = index
}
// 文件上传
async function changeFile(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      let index = parseInt(uploadIndex.value)
      checkData.value[index].fileName = res.data.fileName
      checkData.value[index].origFileName = res.data.origFileName
      checkData.value[index].fileUrl = res.data.url
    }
  } catch (error) {
    console.log(error)
  }
}
// 删除文件
function delFileFn(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = checkData.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        checkData.value[index].fileName = ''
        checkData.value[index].origFileName = ''
        checkData.value[index].fileUrl = ''
        // emit('rowSave', checkData.value[index], index)
      }
    })
  } catch (error) {
    console.log(error)
  }
}

// 统计数据计算
const total = computed(() => item => {
  let result = 0
  switch (item.type) {
    case 'sum':
      checkData.value.forEach(v => {
        if (v[item.key]) {
          result += Number(v[item.key])
        }
      })
      break
    case 'length':
      result = checkData.value.length
      break
    case 'ave':
      let length = checkData.value.length
      let sum = 0
      checkData.value.forEach(v => {
        if (v[item.key]) {
          sum += Number(v[item.key])
        }
      })
      result = sum / length
  }
  return result
})
/*** 合同 验收 table 操作 end */
const emit = defineEmits(['close'])
// 取消
function handleClose() {
  dialogFormVisible.value = false
  emit('close', 'check')
}
// selectDialog 选择数据 ---通知人员
function selectNotifying(val) {
  selectOptionObj.value['nameUUID'] = val.selectData
  formParams.value.nameUUID = val.defaultCheckedKeys
    ? val.defaultCheckedKeys
    : null //前端用的id
  information.value.notifyingOfficer = val.defaultCheckedKeys
    ? getPricipalId(
        selectOptionObj.value['nameUUID'],
        val.defaultCheckedKeys
      ).toString()
    : null //后端用的id
  information.value.name = val.labelData.join(',')
  Notifyingdialog.value.isDialog = false
}

function bidOpeningMsg() {
  const obj = {}
  let resp = true
  for (let i = 0; i < checkData.value.length; i++) {
    const num = [0, 1, 3, 5, 7][Number(information.value.reminderMode)]
    const time =
      information.value.reminderMode &&
      information.value.notifyingOfficer &&
      num
        ? format(new Date(new Date().getTime()), 'yyyy-MM-dd 00:00:00')
        : ''
    obj.receiver = information.value.notifyingOfficer
    console.log(contractTableLits.value, '  contractTableLits.value')
    const contractInfo =
      contractTableLits.value.filter(
        v => v.rcId === formParams.value.rcId
      )[0] || {}
    obj.content = `${props.baseDetail.proName}验收合同${
      contractInfo.contractName ? contractInfo.contractName : ''
    }验收消息登记`
    obj.sendTime = time
    obj.reminderMethod =
      !information.value.reminderMode ||
      (information.value.reminderMode &&
        information.value.reminderMode.length === 0)
        ? ''
        : information.value.reminderMode.toString()
    obj.impSign = '2'
    obj.serviceType = '0'
    obj.urgFlag = '1'
    obj.receiverName = information.value.name
    // obj.followType = information.value.notifyingOfficer
    //   ? information.value.notifyingOfficer
    //   : null
    // obj.followDate = information.value.bidOpeningTime
    obj.urlName = '前往详情'
    obj.title = `关于${props.baseDetail.proName}项目${
      contractInfo.contractName ? contractInfo.contractName : ''
    }验收消息提醒`
    obj.type = '0'
    obj.sender = userStore.user.nickName
    // 项目验收计划
    if (
      !information.value.notifyingOfficer &&
      JSON.stringify(information.value.reminderMode) != '[]'
    ) {
      proxy.$modal.msgWarning('通知人员必填')
      resp = false
      return false
    }
    if (
      information.value.notifyingOfficer &&
      JSON.stringify(information.value.reminderMode) == '[]'
    ) {
      proxy.$modal.msgWarning('提醒方式必填')
      resp = false
      return false
    }
    proMsgData.value.push(obj)
  }

  return resp
}
</script>
<style lang="scss" scoped>
:deep div.el-card__body {
  padding: 15px 20px 0px 20px !important;
  .avue-crud__menu {
    min-height: 0;
  }
}
:deep(.avue-crud__header) {
  display: none !important;
}

.statistics {
  @apply px-20px mb-20px;
  margin: 0 auto 20px;
  .statisticsBox {
    @apply flex justify-end  h-50px items-center px-20px font-bold;
    font-size: 12px;
    background-color: rgb(248, 248, 249);
    border: 1px solid #ebeef5;
    span {
      @apply font-medium;
    }
  }
}
:deep .el-form-item__label {
  left: 5px !important;
}
.avueIcon_style:before {
  content: '*';
  color: var(--el-color-danger);
  left: 3px;
  position: absolute;
  font-size: 18px;
}
.fileIcon_style:before {
  top: 20px;
}
</style>
